package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import io.reactivex.rxjava3.core.Single;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // redisson的锁对象
    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static{
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

//    // 单线程的线程池
//    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
//
//    // 此注解是在项目构建之后就运行的意思
//    // 这里是构建之后运行该线程
//    @PostConstruct
//    public void init(){
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//    }
//
//    private class VoucherOrderHandler implements Runnable{
//
//        @Override
//        public void run() {
//            String queuename = "stream.orders";
//            while (true){
//                // 1.获取消息队列中的订单信息
//                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
//                        Consumer.from("g1", "c1"),
//                        StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
//                        StreamOffset.create(queuename, ReadOffset.lastConsumed())
//                );
//                // 2.判断纤细获取是否成功  失败说明没有消息,继续下一次循环
//                if(list == null || list.isEmpty()){
//                    continue;
//                }
//                // 2.2成功可以下单
//                MapRecord<String, Object, Object> record = list.get(0);
//                Map<Object, Object> values = record.getValue();
//                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
//
//                handleVoucherOrder(voucherOrder);
//                // 3.ACK确认
//                stringRedisTemplate.opsForStream().acknowledge(queuename,"g1",record.getId());
//            }
//        }
//    }

//    @Override
//    @Transactional
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
//        // 使用阻塞队列异步的对订单进行处理，这样效率更高
//        Long userid = UserHolder.getUser().getId();
//        // 获取订单id
//        long orderid = redisIdWorker.nextId("order");
//        // 首先使用lua脚本，判断用户是否有资格购买
//        Long succees = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userid.toString(),String.valueOf(orderid));
//        int r = succees.intValue();
//        // 没资格就返回异常信息，有资格就后续交给另一个线程进行数据库处理
//        if(r!=0){
//            return Result.fail(r == 1?"库存不足":"用户下过单了");
//        }
//
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setVoucherId(voucherId);
//        voucherOrder.setId(orderid);
//        voucherOrder.setUserId(userid);
//
//        return Result.ok(orderid);
//    }
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束");
        }

        if (voucher.getStock()<1) {
            return Result.fail("库存不足");
        }

        Long userid = UserHolder.getUser().getId();

        // 这是我们自己写的锁，因为要理解锁的原理，但是实际用的时候还是要用redisson的锁，既方便又安全
    //        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userid, stringRedisTemplate);

        RLock lock = redissonClient.getLock("lock:order:" + userid);

        // 三个参数，锁等待时间，自动释放锁的时间，时间的单位
        boolean islock = lock.tryLock(1,10, TimeUnit.SECONDS);

        if(!islock){
            return Result.fail("一个人只能下一单");
        }

        try {
            // 获取代理对象，不然当前对象调用事务函数，事务会失效
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId){
        Long userid = UserHolder.getUser().getId();
        int cnt = query().eq("user_id", userid).eq("voucher_id", voucherId).count();
        if (cnt > 0) {
            return Result.fail("用户已经下过单了");
        }

        boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
                    .eq("voucher_id", voucherId)  // eq相当于sql中的where
                    .gt("stock", 0)   // 乐观锁
                    .update();
        if (!success) {
            return Result.fail("库存不足");
        }

         long id = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(id);

        voucherOrder.setUserId(userid);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        return Result.ok(id);
    }
}
